{-
Arquivo de entrada. Gerencia IO e chama as funções próprias.
-}

import SourceData
import SchemeParser

import System.Environment
import System.FilePath
import qualified Data.Map as Map


main :: IO ()
main = do
  args <- getArgs
  case args of
    (mode:rest) ->
        case mode of
          "diff" ->
              let (f1:f2:_)    = rest
                  (ext1, ext2) = ((takeExtension f1), (takeExtension f2)) in
              if ext1 /= ext2
              then
                  error "Files must have same extension!"
              else
                  diff (f1,f2) ext1
          "patch" ->
              let (f1:f2:f3:_)             = rest
                  (ext1: ext2: ext3:[])    = map takeExtension [f1,f2,f3] in
              if ext1 /= ext2 || ext2 /= ext3
              then
                  error "Files must have same extension!"
              else
                  patch (f1,f2,f3) ext1
          "version" -> putStrLn "ydiff - \"yntelligent\" diff 0.1"
          otherwise ->
               putStrLn helpMessage
    otherwise -> putStrLn helpMessage

helpMessage :: String
helpMessage = "commands:\n  diff file1 file2\n  patch file1 file2 file3\n  version"

diff :: (FilePath, FilePath) -> String -> IO ()
diff (f1, f2) ext =
    do
      file1 <- readFile f1
      file2 <- readFile f2
      print $ diffCode (parser ext file1) (parser ext file2)
--      print $ parser ext file2

patch :: (FilePath, FilePath, FilePath) -> String -> IO ()
patch (f1, f2, f3) ext =
    do
      file1 <- readFile f1
      file2 <- readFile f2
      file3 <- readFile f3
      print $ patchTree (parser ext file3) (diffCode' (parser ext file1) (parser ext file2))

parser ext = let a = Map.lookup ext (Map.fromList
                                            [(".scm", parseScheme)])
             in
             case a of
               (Just b) -> b
               (Nothing) -> error "Parser not implemented yet"

--test = diff ("t3.scm","t4.scm")